#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <filesystem> //C++17
#include <sstream>
#include <fstream>
#include <memory>
#include <ctime>
#include <unistd.h>
#include "mutex.hpp"

namespace LogModule
{
    using namespace MutexModule;
    const std::string gsep = "\r\n";
    class LogStrateegy
    {
    public:
        ~LogStrateegy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    // 显示器打印，子类
    class ConsolelogStrategy : public LogStrateegy
    {
    public:
        ConsolelogStrategy() {

        };
        void SyncLog(const std::string &message) override
        {
            LockGuard lockguard(_mutex);
            std::cout << message << gsep;
        }
        ~ConsolelogStrategy() {};

    private:
        Mutex _mutex;
    };

    // 文件打印，子类
    const std::string defaultpath = "./log";
    const std::string defaultfile = "my.log";
    class FileLogStrategy : public LogStrateegy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &file = defaultfile)
            : _path(path), _file(file)
        {
            LockGuard lockguard(_mutex);
            if (std::filesystem::exists(_path))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }

        void SyncLog(const std::string &message) override
        {
            LockGuard lockguard(_mutex);
            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _file;
            std::ofstream out(filename, std::ios::app);
            if (!out.is_open())
            {
                return;
            }

            out << message << gsep;
            out.close();
        };

        ~FileLogStrategy()
        {
        }

    private:
        std::string _file;
        std::string _path;
        Mutex _mutex;
    };

    enum class LogLevel // 强枚举类型
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    std::string LevelToString(const LogLevel &le)
    {
        switch (le)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }
    std::string GetTime()
    {
        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr, &curr_tm);
        char timebuffer[128];
        snprintf(timebuffer, sizeof(timebuffer),"%4d-%02d-%02d %02d:%02d:%02d",
            curr_tm.tm_year+1900,
            curr_tm.tm_mon+1,
            curr_tm.tm_mday,
            curr_tm.tm_hour,
            curr_tm.tm_min,
            curr_tm.tm_sec
        );
        return timebuffer;
    }

    class Logger
    {
    public:
        Logger()
        {
            EnableConsoleLogStrategy();
        }
        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }
        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsolelogStrategy>();
        }

        class logmessage
        {
        public:
            logmessage(const LogLevel &level,const std::string &src_name, int line_num,Logger& logger)
                : _curr_time(GetTime()), _pid(getpid()), _level(level), _src_name(src_name), _line_num(line_num),_logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _curr_time << "]"
                   << "[" << LevelToString(_level) << "]"
                   << "[" << _pid << "]"
                   << "[" << _line_num << "]";

                _loginfo=ss.str();
            };
            template<typename T>
            logmessage& operator<<(const T& info)
            {
                std::stringstream ss;
                ss<<info;
                _loginfo+=ss.str();
                return *this;
            }
            ~logmessage()
            {
                if(_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_loginfo);
                }
            }

        private:
            std::string _curr_time;
            LogLevel _level;
            std::string _src_name;
            pid_t _pid;
            size_t _line_num;
            std::string _loginfo;
            Logger &_logger;
        };

        logmessage operator()(LogLevel level,const std::string& src_name,int line)
        {
            return logmessage(level,src_name,line,*this);
        }

        ~Logger()
        {
        }

    private:
        std::unique_ptr<LogStrateegy> _fflush_strategy;
    };
    Logger logger;


    //使用宏，简化用户操作
    #define LOG(level) logger(level,__FILE__,__LINE__)
    #define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
    #define Enable_File_Log_Strategy()  logger.EnableFileLogStrategy()
}